#include "Sprite.h"
namespace Engine {
	Sprite::Sprite()
	{
		this->sprimage = NULL;
		this->tximage = NULL;
		this->imageLoaded = false;
		this->setPosition(0.0f,0.0f);
		this->setVelocity(0.0f,0.0f);
		this->state = 0;
		this->direction = 0;
		this->width = 1;
		this->height = 1;
		this->curframe = 0;
		this->totalframes = 1;
		this->animdir = 1;
		this->animcolumns = 1;
		this->framestart = 0;
		this->frametimer = 0;
		this->animcolumns = 1;
		this->animstartx = 0;
		this->animstarty = 0;
		this->faceAngle = 0;
		this->moveAngle = 0;
		this->rotation = 0;
		this->scaling = 1.0f;
		this->color = sf::Color(0,0,0);
		this->movetimer = 16;
		this->movestart = 0;
		this->collidable = true;
		this->collisionMethod = COLLISION_RECT;
	}
	Sprite::~Sprite() 
	{
		if (imageLoaded)
		{
			delete sprimage;
			delete tximage;
		}
	}
	void Sprite::setImage(std::string filename)
	{
		this->tximage = textureManager->getTexture(filename);
		this->sprimage->SetTexture(*tximage);
		this->setWidth(tximage->GetWidth());
		this->setHeight(tximage->GetHeight());
		this->imageLoaded = false;
	}
	void Sprite::draw(sf::RenderWindow &window)
	{
		//calculate source frame location
		int fx = (this->curframe % this->animcolumns) * this->width;
		int fy = (this->curframe / this->animcolumns) * this->height;
		sf::Rect<int> srcRect(fx,fy, fx+this->width, fy+this->height);
		sprimage->SetTextureRect(srcRect);
		//draw the sprite frame
		window.Draw(*sprimage);
	}
	void Sprite::move()
	{
		if (movetimer > 0) 
		{
			if (moveClock.GetElapsedTime().AsMilliseconds() > movetimer) 
			{
				//reset move timer
				moveClock.Restart();
				//move sprite by velocity amount
				this->setX(this->getX() + this->velocity.x);
				this->setY(this->getY() + this->velocity.x);
			}
		}
		else 
		{
			//no movement timer- -update at cpu clock speed
			this->setX(this->getX() + this->velocity.x);
			this->setY(this->getY() + this->velocity.y);
		}
	}
	void Sprite::animate()
	{
		//update frame based on animdir
		if (frametimer > 0)
		{
			if (frameClock.GetElapsedTime().AsMilliseconds() > frametimer) 
			{
				//reset animation timer
				frameClock.Restart();
				curframe += animdir;
				//keep frame within bounds
				if (curframe < 0) curframe = totalframes-1;
				if (curframe > totalframes-1) curframe = 0;
			}
		}
		else 
		{
			//no animation timer- -update at cpu clock speed
			curframe += animdir;
			if (curframe < 0) curframe = totalframes-1;
			if (curframe > totalframes-1) curframe = 0;
		}
	}
	void Sprite::cleanUp()
	{
		delete sprimage;
		delete tximage;
	}
}